package com.sysu.homework.DAO.Impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.sysu.homework.DAO.StudentDAO;
import com.sysu.homework.model.Group;
import com.sysu.homework.model.Student;

@Component("studentDAO")
public class StudentDAOImpl implements StudentDAO {
	private HibernateTemplate hibernateTemplate;
	
	@Override
	public int save(Student student) {
		if(hibernateTemplate.save(student) != null)
			return 1;
		return -1;
	}

	@Override
	public boolean isExist(int studentId) {
		List<Student> students = new ArrayList<Student>();
		students = hibernateTemplate.find("from Student student where student.id='"+studentId+"'");
		if(students.size()>0)
			return true;
		return false;
	}

	@Override
	public int getGroupId(int studentId) {
		Student student = (Student)getHibernateTemplate().load(Student.class, studentId);
		Group group = student.getGroup();
		if(group != null)
			return group.getId();
		return -1;
	}

	@Override
	public Student getStudentById(int studentId) {
		Student student = (Student)getHibernateTemplate().load(Student.class, studentId);
		if(student != null)
			return student;
		return null;
	}
	
	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Override
	public boolean isValid(int id, String password) {
		Student student = (Student)hibernateTemplate.get(Student.class, id);
		if (student != null && student.getPassword().equals(password))
			return true;
		return false;
	}

	@Override
	public int getCourseId(int studentId) {
		Student student = (Student)hibernateTemplate.get(Student.class, studentId);
		if (student != null)
			return student.getCourse().getId();
		return 0;
	}

	@Override
	public int saveGroup(Group group) {
		if (hibernateTemplate.save(group)!=null)
			return 1;
		return -1;
	}

	@Override
	public int updateStudent(Student student) {
		hibernateTemplate.saveOrUpdate(student);
		hibernateTemplate.flush();
		return 1;
	}

	@Override
	public List<Group> getAllGroups() {
		List<Group> groups = new ArrayList<Group>();
		groups = hibernateTemplate.find("from Group");
		return groups;
	}

	

}
